package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.ReportService;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private ReportService reportService;
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        //获取前一个月的时间
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH,-23);
            Map<String,Object> map = new HashMap<>();
            List<String> list = new ArrayList<>();
            //遍历获取中间12个月的时间
            for (int i = 1; i <=12 ; i++) {
                calendar.add(Calendar.MONTH,1);
                Date time = calendar.getTime();
                //把时间转化为只有年月的
                list.add(new SimpleDateFormat("yyyy.MM").format(time));
            }
            //添加月份
            map.put("months",list);
            //根据月份查询对应用户人数
            List<Integer> memberReport = reportService.getMemberReport(list);
            map.put("memberCount",memberReport);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }
    /**
     *
     * 饼状数据
     * */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        return reportService.getSetmealReport();
    }

    /**
     * 获取运营数据
     * */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        return reportService.getBusinessReportData();
    }

    /*
    * 导出excel
    * */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            Result data = reportService.getBusinessReportData();
            Map<String,Object> map = (Map<String, Object>) data.getData();
            //获取文件的真实路径
            //File.separator获取/或反斜杠
            String realPath = request.getSession().getServletContext().getRealPath("template") + File.separator + ("report_template.xlsx");
            //获取excel模板文件
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(realPath)));
            //获取第几张表
            XSSFSheet sheetAt = workbook.getSheetAt(0);
            //获取第几行
            XSSFRow row = sheetAt.getRow(2);
            //获取第几个单元格并设置他
            row.getCell(5).setCellValue((String) map.get("reportDate"));//日期

            row = sheetAt.getRow(4);
            row.getCell(5).setCellValue((Integer)map.get("todayNewMember"));//新增会员数
            row.getCell(7).setCellValue((Integer)map.get("totalMember"));//总会员数

            row = sheetAt.getRow(5);
            row.getCell(5).setCellValue((Integer)map.get("thisWeekNewMember"));//本周新增会员数
            row.getCell(7).setCellValue((Integer)map.get("thisMonthNewMember"));//本月新增会员数

            row = sheetAt.getRow(7);
            row.getCell(5).setCellValue((Integer)map.get("todayOrderNumber"));//今日预约数
            row.getCell(7).setCellValue((Integer)map.get("todayVisitsNumber"));//今日已经到诊数

            row = sheetAt.getRow(8);
            row.getCell(5).setCellValue((Integer)map.get("thisWeekOrderNumber"));//本周预约数
            row.getCell(7).setCellValue((Integer)map.get("thisWeekVisitsNumber"));//本周已经到诊数

            row = sheetAt.getRow(9);
            row.getCell(5).setCellValue((Integer)map.get("thisMonthOrderNumber"));//本月预约数
            row.getCell(7).setCellValue((Integer)map.get("thisMonthVisitsNumber"));//本月已经到诊数

            int rowId = 12;
            //获取热门套餐
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) map.get("hotSetmeal");
            for (Map<String, Object> objectMap : hotSetmeal) {
                BigDecimal proportion = (BigDecimal) objectMap.get("proportion");
                row = sheetAt.getRow(rowId++);
                row.getCell(4).setCellValue((String) objectMap.get("name"));//套餐名称
                row.getCell(5).setCellValue((Long) objectMap.get("setmeal_count"));//套餐数量
                row.getCell(6).setCellValue(proportion.doubleValue());//套餐百分比  转化为double
            }
            //输出excel文件 使用浏览器输出才可以
            response.setContentType("application/vnd.ms-excel");//设置编码
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");//设置文件下载弹出文件框
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            //关流
            outputStream.flush();
            workbook.close();
            outputStream.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /*
    * 导出pdf文件
    * */
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request,HttpServletResponse response){
        //获取jrxml文件路径
        String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + ("health_business3.jrxml");
        try {
            String jasperPath =
                    request.getSession().getServletContext().getRealPath("template") + File.separator + ("health_business3.jasper");
//编译模板
            //JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
//构造数据
            Result data = reportService.getBusinessReportData();
            Map<String,Object> map = (Map<String, Object>) data.getData();
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) map.get("hotSetmeal");
//填充数据
            JasperPrint jasperPrint =
                    JasperFillManager.fillReport(jasperPath,
                            map,
                            new JRBeanCollectionDataSource(hotSetmeal));
            //JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,paramters,new JRBeanCollectionDataSource(list));
            //设置下载文件编码
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition","attachment;filename=report.pdf");
//输出文件
            ServletOutputStream out = response.getOutputStream();
            //JasperExportManager.exportReportToPdfFile(jasperPrint,pdfPath);
            //使用流输出
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
